package com.thiswhyme.openfeign.server.api.dto.serializer;

import com.google.gson.*;
import com.google.gson.reflect.TypeToken;
import com.thiswhyme.common.expection.BusinessException;
import com.thiswhyme.common.response.ResponseVo;
import com.thiswhyme.openfeign.gson.adapter.GsonBizAdapter;
import com.thiswhyme.openfeign.server.api.dto.BaseDto;
import com.thiswhyme.openfeign.server.api.dto.StudentDto;
import com.thiswhyme.openfeign.server.api.dto.TeacherDto;
import com.thiswhyme.openfeign.server.api.dto.UserType;

import java.lang.reflect.Type;

/**
 * @author: thiswhyme
 * @date: 2020/8/24
 */
public class ResponseVoBaseDtoAdapter implements GsonBizAdapter<ResponseVo<BaseDto>> {
    @Override
    public Type getType() {
        return new TypeToken<ResponseVo<BaseDto>>(){}.getType();
    }

    @Override
    public Class getClazz() {
        return null;
    }

    @Override
    public ResponseVo<BaseDto> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        JsonObject jsonObject = json.getAsJsonObject();
        Type type = null;
        if(null != jsonObject) {
            JsonObject data = jsonObject.getAsJsonObject("data");
            //此处根据DemoType枚举判断反序列化成哪种子类
            if(null != data) {
                JsonPrimitive userType = data.getAsJsonPrimitive("userType");
                if(UserType.STUDENT.name().equals(userType.getAsString())) {
                    type = new TypeToken<ResponseVo<StudentDto>>() {}.getType();
                } else if(UserType.TEACHER.name().equals(userType.getAsString())) {
                    type = new TypeToken<ResponseVo<TeacherDto>>() {}.getType();
                }
            }
        }
        if(null == type) {
            throw new BusinessException("未指定转换类型，无法转换");
        }
        return context.deserialize(jsonObject, type);
    }

    @Override
    public JsonElement serialize(ResponseVo<BaseDto> src, Type typeOfSrc, JsonSerializationContext context) {
        return context.serialize(src);
    }
}
